//
//  ForgetPasswordView.m
//  AppleMarket
//
//  Created by yangy on 26/10/2018.
//  Copyright © 2018 szgsy. All rights reserved.
//

#import "ForgetPasswordView.h"
// view
#import "BH_UnderLineTextField.h"
// viewModel
#import "ForgetViewModel.h"

@interface ForgetPasswordView()
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) BH_UnderLineTextField *accountTF; // 账号
@property (nonatomic, strong) BH_UnderLineTextField *codeTF;   // 验证码
@property (nonatomic, strong) BH_UnderLineTextField *passwordTF;    // 密码
@property (nonatomic, strong) BH_UnderLineTextField *password2TF;   // 确认密码
@property (nonatomic, strong) UIButton *commitButton;               // 提交
@property (nonatomic, strong) UIButton *eyeButton;                  // 隐藏密码
@property (nonatomic, strong) UIButton *codeButton;                 // 发送验证码
@property (nonatomic, assign) NSInteger time;
@property (nonatomic, strong) RACDisposable *disposable;
@property (nonatomic, strong) ForgetViewModel *viewModel;
@end

@implementation ForgetPasswordView

- (instancetype)initWithFrame:(CGRect)frame viewModel:(id) viewModel
{
    self = [super initWithFrame:frame];
    if(self){
        _viewModel = viewModel;
        [self initUI];
        [self bindViewModel];
    }
    return self;
}

- (void) bindViewModel
{
    RAC(_viewModel,accountStr_) = _accountTF.rac_textSignal;
    RAC(_viewModel,codeStr_) = _codeTF.rac_textSignal;
    RAC(_viewModel,passwordStr_) = _passwordTF.rac_textSignal;
    
    RAC(_commitButton,enabled) = [RACSignal combineLatest:@[RACObserve(_accountTF, text),RACObserve(_codeTF, text),RACObserve(_passwordTF, text)] reduce:^id (NSString *acc,NSString *code,NSString *pwd){
        return @(acc.length && code.length && pwd.length);
    }];
    RAC(_commitButton,backgroundColor) = [RACSignal combineLatest:@[RACObserve(_accountTF, text),RACObserve(_codeTF, text),RACObserve(_passwordTF, text)] reduce:^id (NSString *acc,NSString *code,NSString *pwd){
        return (acc.length && code.length && pwd.length) ? kColorWithHex(0x3291EB) : kColorWithHex(0xADB7C1);
    }];
}

- (void) initUI
{
    [self addSubview:self.titleLabel];
    [self addSubview:self.accountTF];
    [self addSubview:self.codeTF];
    [self addSubview:self.passwordTF];
    [self addSubview:self.password2TF];
    [self addSubview:self.commitButton];
    [self setViewLayout];
}

- (void) setViewLayout
{
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self).offset(30);
        make.left.mas_equalTo(self).offset(31);
    }];
    
    [_accountTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(55);
        make.left.mas_equalTo(self.titleLabel.mas_left);
        make.right.mas_equalTo(self.mas_right).offset(-31);
    }];
    
    [_codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.accountTF.mas_bottom).offset(18);
        make.left.mas_equalTo(self.titleLabel.mas_left);
        make.right.mas_equalTo(self.accountTF.mas_right);
    }];
    
    [_passwordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.codeTF);
        make.top.mas_equalTo(self.codeTF.mas_bottom).offset(18);
    }];
    
    [_password2TF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.passwordTF);
        make.top.mas_equalTo(self.passwordTF.mas_bottom).offset(18);
    }];
    
    [_commitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.password2TF);
        make.top.mas_equalTo(self.password2TF.mas_bottom).offset(18);
        make.height.mas_equalTo(40);
    }];
    
}

- (UILabel *)titleLabel
{
    if(!_titleLabel){
        _titleLabel = [UILabel cm_labelWithText:@"找回密码" font:kFontBold(26) textColor:kColorWithHex(0x0E304C)];
    }
    return _titleLabel;
}


- (BH_UnderLineTextField *)accountTF
{
    if(!_accountTF){
        _accountTF = [[BH_UnderLineTextField alloc] initWithFrame:CGRectMake(30, 0, k_ScreenWidth - 60, 44)];
        _accountTF.font = kFont(13);
        _accountTF.placeholder = @"手机号码/邮箱账号";
        _accountTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        _accountTF.autocapitalizationType = UITextAutocapitalizationTypeNone;        //首字母不大写
        [_accountTF.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
            if(self.accountTF.error.length){
                self.accountTF.error = @"";
            }
        }];
    }
    return _accountTF;
}

- (BH_UnderLineTextField *)codeTF
{
    if(!_codeTF){
        _codeTF = [[BH_UnderLineTextField alloc] initWithFrame:CGRectMake(30, 0, k_ScreenWidth - 60, 44)];
        _codeTF.placeholder = @"验证码";
        _codeTF.font = kFont(13);
        _codeTF.keyboardType = UIKeyboardTypeNumberPad;
        _codeTF.rightView = self.codeButton;
        _codeTF.rightViewMode = UITextFieldViewModeAlways;
        _codeTF.autocapitalizationType = UITextAutocapitalizationTypeNone;
        [_codeTF.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
            if(self.codeTF.error.length){
                self.codeTF.error = @"";
            }
        }];
    }
    return _codeTF;
}
- (BH_UnderLineTextField *)passwordTF
{
    if(!_passwordTF){
        _passwordTF = [[BH_UnderLineTextField alloc] initWithFrame:CGRectMake(30, 0, k_ScreenWidth - 60, 44)];
        _passwordTF.font = kFont(13);
        _passwordTF.placeholder = @"6~20位，包括数字、大小写字母、特殊字符";
        _passwordTF.secureTextEntry = YES;
        _passwordTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        _passwordTF.autocapitalizationType = UITextAutocapitalizationTypeNone;        //首字母不大写
        _passwordTF.rightViewMode = UITextFieldViewModeWhileEditing;
        [_passwordTF.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
            if(self.passwordTF.error.length){
                self.passwordTF.error = @"";
            }
        }];
    }
    return _passwordTF;
}
- (BH_UnderLineTextField *)password2TF
{
    if(!_password2TF){
        _password2TF = [[BH_UnderLineTextField alloc] initWithFrame:CGRectMake(30, 0, k_ScreenWidth - 60, 44)];
        _password2TF.font = kFont(13);
        _password2TF.placeholder = @"确认登录密码";
        _password2TF.secureTextEntry = YES;
        _password2TF.clearButtonMode = UITextFieldViewModeWhileEditing;
        _password2TF.autocapitalizationType = UITextAutocapitalizationTypeNone;        //首字母不大写
        _password2TF.rightView = self.eyeButton;
        _password2TF.rightViewMode = UITextFieldViewModeWhileEditing;
        [_password2TF.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
            if(self.password2TF.error.length){
                self.password2TF.error = @"";
            }
        }];
    }
    return _password2TF;
}

- (UIButton *)commitButton
{
    if(!_commitButton){
        _commitButton = [UIButton cm_ButtonWithTitle:@"提交" font:kFont(14) titleColor:[UIColor whiteColor] bgColor:kColorWithHex(0x3291EB)];
        [[_commitButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if(![self.accountTF.text bh_IsValidPhoneNumber] && ![self.accountTF.text bh_IsEmailAddress]){
                self.accountTF.error = @"账号格式错误";
            }else if(self.passwordTF.text.length < 6 || self.passwordTF.text.length > 20){
                self.passwordTF.error = @"密码错误";
            }else if(self.password2TF.text.length < 6 || self.password2TF.text.length > 20){
                self.password2TF.error = @"密码错误";
            }else if(![self.password2TF.text isEqualToString:self.passwordTF.text]){
                [SVProgressHUD showInfoWithStatus:@"两次密码不一致，请重新输入"];
            }else{
                [self.viewModel.commitClickSubject sendNext:nil];
            }
        }];
    }
    return _commitButton;
}


- (UIButton *)eyeButton
{
    if(!_eyeButton){
        _eyeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_eyeButton setImage:[UIImage imageNamed:@"eye"] forState:UIControlStateNormal];
        _eyeButton.frame = CGRectMake(0, 0, 44, 44);
        @weakify(self);
        [[_eyeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            x.selected = !x.isSelected;
            self.passwordTF.secureTextEntry = self.password2TF.secureTextEntry = !x.isSelected;
            self.passwordTF.text = [self.passwordTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            self.password2TF.text = [self.passwordTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        }];
    }
    return _eyeButton;
}

- (UIButton *)codeButton
{
    if(!_codeButton){
        _codeButton = [UIButton cm_ButtonWithTitle:@"获取验证码" font:kFont(13) titleColor:kColorWithHex(0x3291EB)];
        _codeButton.frame = CGRectMake(0, 0, 88, 44);
        _codeButton.titleLabel.textAlignment = NSTextAlignmentRight;
        [[_codeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if(self.accountTF.text.length == 0){
                [SVProgressHUD showInfoWithStatus:@"请输入手机号或邮箱账号"];
                return;
            }
            if(![self.accountTF.text bh_IsValidPhoneNumber] && ![self.accountTF.text bh_IsEmailAddress]){
                self.accountTF.error = @"账号格式不正确";
                return;
            }
            [self.viewModel.sendCodeClickSubject sendNext:nil];
            x.enabled = NO;
            self.time = 60;
            self.disposable = [[RACSignal interval:1.0 onScheduler:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSDate * _Nullable x) {
                self.time -- ;
                NSString *title = self.time > 0 ? [NSString stringWithFormat:@"%lds",self.time] : @"重新发送";
                UIColor *bgColor =  self.time > 0 ? kColorWithHex(0xADB7C1) : kColorWithHex(0x3291EB);
                [self.codeButton setTitle:title forState:UIControlStateNormal | UIControlStateDisabled];
                [self.codeButton setTitleColor:bgColor forState:UIControlStateNormal | UIControlStateDisabled];
                self.codeButton.enabled = (self.time <= 0) ? YES : NO;
                if(self.time == 0){
                    [self.disposable dispose];
                }
            }];
        }];
    }
    return _codeButton;
}


@end
